package com.wang.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.wang.constant.ErrorCode;
import com.wang.constant.FileUploadBizEnum;
import com.wang.exception.BusinessException;
import com.wang.param.FileUploadParam;
import com.wang.result.BaseResponse;
import com.wang.result.ResultUtils;
import com.wang.user.service.user.UserService;
import com.wang.util.FileUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;

@RestController
@RequestMapping("/file")
@Api(tags = "文件上传")
public class FileController {

    @Resource
    private UserService userService;
    @Autowired
    private FileUploadUtils fileUploadUtils;

    @Value("${file.upload.path}")
    private String uploadDir;


    /**
     * 文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiOperation(value = "上传")
    public BaseResponse<String> uploadFile(MultipartFile file, @RequestParam(value = "type")String type, HttpServletRequest request) throws IOException, ServletException {

        MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("pics");
        if(ObjectUtil.isNull(file)){
            file = multipartFile;
        }

        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(type);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        fileUploadUtils.validFile(file);
        // 5. 创建目标文件目录 用户id+当前时间戳
        String targetDir = uploadDir;
        // 创建目标文件目录
        File dir = new File(targetDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 6. 生成唯一的文件名，避免文件名冲突
        String fileName = IdUtil.randomUUID() + "-" +file.getOriginalFilename();

        String targetFilePath = targetDir + fileName;
        File targetFile = new File(targetFilePath);
        if (!targetFile.createNewFile()) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        }
        // 使用缓冲流保存文件
        try (BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile))) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
        }
        // 更新FileInfo中的文件路径信息
        String path = "localhost:8066" + "/static/images/" + fileName;
        return ResultUtils.success(path);
    }


    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}